package utils

import (
	"fmt"
	"strings"
	"time"
)

const (
	TimeDefaultFormat = "2006-01-02 15:04:05" // 日志输出默认格式
)

var MsgQueue = make(chan []byte, 1024)
var Done = make(chan bool, 1)

var LogLevelMap = map[int]string{
	1: "EMER",
	2: "ALRT",
	3: "CRIT",
	4: "EROR",
	5: "WARN",
	6: "INFO",
	7: "DEBG",
	8: "TRAC",
}

func formatMsg(level int, f interface{}, v ...interface{}) []byte {
	var msg string
	switch f.(type) {
	case string:
		msg = f.(string)
		if len(v) == 0 {
			return []byte(msg)
		}
		if strings.Contains(msg, "%") && !strings.Contains(msg, "%%") {
			//format string
		} else {
			//do not contain format char
			msg += strings.Repeat(" %v", len(v))
		}
	default:
		msg = fmt.Sprint(f)
		if len(v) == 0 {
			return []byte(msg)
		}
		msg += strings.Repeat(" %v", len(v))
	}

	when := time.Now()
	msgStr := when.Format(TimeDefaultFormat) + " [" + LogLevelMap[level] + "] " + fmt.Sprintf(msg, v...)
	return []byte(msgStr)
}

// Error logs a message at error level.
func Error(f interface{}, v ...interface{}) {
	level := 4
	MsgQueue <- formatMsg(level, f, v...)
}

// Info logs a message at info level.
func Info(f interface{}, v ...interface{}) {
	level := 6
	MsgQueue <- formatMsg(level, f, v...)
}

// Notice logs a message at debug level.
func Debug(f interface{}, v ...interface{}) {
	level := 7
	MsgQueue <- formatMsg(level, f, v...)
}
